﻿#include <QResizeEvent>

#include "CefWebEngineCore/CefWebEngine.h"
#include "CefWebEngineWidgets/CefWebEngineView.h"

CefWebEngineView::CefWebEngineView(QWidget *parent)
    : QWidget(parent),
    mpage(nullptr),
    mfixWindowTitle(false)
{
    setFocusPolicy(Qt::WheelFocus);
    setMouseTracking(true);
}

CefWebEngineView::~CefWebEngineView()
{
}

void CefWebEngineView::setPage(CefWebEnginePage *page)
{
    if (mpage)
        delete mpage;

    mpage = page;
    if (page)
    {
        if(!page->parent())
            page->setParent(this);
        
        connect(page, &CefWebEnginePage::loadStarted, this, &CefWebEngineView::loadStarted);
        connect(page, &CefWebEnginePage::loadProgressChanged, this, &CefWebEngineView::loadProgressChanged);
        connect(page, &CefWebEnginePage::loadFinished, this, &CefWebEngineView::loadFinished);
        connect(page, &CefWebEnginePage::errorOccurred, this, &CefWebEngineView::errorOccurred);

        connect(page, &CefWebEnginePage::titleChanged, this, &CefWebEngineView::titleChanged);
        connect(page, &CefWebEnginePage::urlChanged, this, &CefWebEngineView::urlChanged);
        connect(page, &CefWebEnginePage::faviconUrlChanged, this, &CefWebEngineView::faviconUrlChanged);
        connect(page, &CefWebEnginePage::toolTipChanged, this, &CefWebEngineView::toolTipChanged);
        connect(page, &CefWebEnginePage::cursorChanged, this, &CefWebEngineView::cursorChanged);

        connect(page, &CefWebEnginePage::newWindowRequested, this, &CefWebEngineView::newWindowRequested, Qt::BlockingQueuedConnection);
        connect(page, &CefWebEnginePage::resizeRequested, this, &CefWebEngineView::resizeRequested, Qt::BlockingQueuedConnection);
        connect(page, &CefWebEnginePage::fullScreenRequested, this, &CefWebEngineView::fullScreenRequested);
        connect(page, &CefWebEnginePage::renderProcessTerminated, this, &CefWebEngineView::renderProcessTerminated);

        if (!mfixWindowTitle)
        {
            setWindowTitle(page->title());
            connect(page, &CefWebEnginePage::titleChanged, this, &CefWebEngineView::setWindowTitle);
        }
        page->resize(size() * devicePixelRatioF());

        // frameless mode connections
        // connect(page, &CefWebEnginePage::cursorChanged, this, &CefWebEngineView::setCursor);
    }
}

CefWebEnginePage *CefWebEngineView::setupEmptyPage(const QUrl &url)
{
    if (mpage)
        return mpage;
    setPage(CefWebEngine::instance()->createPage(url, winId(), false));
    return page();
}

void CefWebEngineView::load(const QUrl &url)
{
    if (mpage)
        mpage->load(url);
    else
        setPage(CefWebEngine::instance()->createPage(url, winId()));
}

void CefWebEngineView::resizeEvent(QResizeEvent *ev)
{
    QWidget::resizeEvent(ev);
    if (mpage)
        mpage->resize(ev->size() * devicePixelRatioF());
}